﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Business.Compta;
using DAO.Compta;
using Compta;
using System.IO;
using Manageo;

namespace Compta
{
    /// <summary>
    /// Interaction logic for StatementsUI.xaml
    /// </summary>
    public partial class StatementsUI : UserControl
    {
        int idAccount = -1;
        private ObservableRangeCollection<ComptaStatement> statements = new ObservableRangeCollection<ComptaStatement>();
        private ObservableRangeCollection<Account> accounts = new ObservableRangeCollection<Account>();


        public ObservableRangeCollection<Account> Accounts
        {
            get
            {
                return new ObservableRangeCollection<Account>(accounts);
            }
        }
        public ObservableRangeCollection<ComptaStatement> Statements
        {
            get
            {
                if (statements == null)
                {
                    this.statements =
                        new ObservableRangeCollection<ComptaStatement>(ComptaStatementsDAO.getStatementsForAccount(idAccount));
                }
                return statements;
            }
        }

        public StatementsUI(int idUser)
        {
            InitializeComponent();
            accounts.ReplaceRange(ComptaAccountsDAO.getAllAccounts(idUser));
            date.DateTime = DateTime.Now;
        }

        private void TableView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                DevExpress.Wpf.Grid.TableView view = (DevExpress.Wpf.Grid.TableView)sender;
                if (view.ActiveEditor == null || !view.ActiveEditor.IsEditorActive)
                    DeleteStatement(view.FocusedRowHandle);
            }
        }

        private void DeleteStatement(int rowHandle)
        {
            int listIndex = this.gridControl1.GetRowListIndex(rowHandle);
            ObservableRangeCollection<ComptaStatement> list =
                (ObservableRangeCollection<ComptaStatement>)this.gridControl1.DataSource;
            if (listIndex >= 0)
            {
                ComptaStatement line = list[listIndex];
                try
                {
                    ComptaStatementsDAO.DeleteStatement(line);
                    list.RemoveAt(listIndex);
                }
                catch (Exception e)
                {
                    MessageBox.Show("error while deleting statement (id = " + line.Id + ")\n" + e.StackTrace, "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void gridControl1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            int rowHandle = this.gridControl1.View.GetRowHandleByMouseEventArgs(e);
            if (rowHandle != DevExpress.Wpf.Grid.GridControl.InvalidRowHandle)
            {
                if (!this.gridControl1.IsGroupRowHandle(rowHandle))
                {
                    String tempDir = Environment.GetEnvironmentVariable("TEMP");

                    ComptaStatement statement = (ComptaStatement)this.gridControl1.GetRow(rowHandle);

                    try
                    {
                        byte[] file = ComptaStatementsDAO.getStatement(statement.Id);
                        MemoryStream ms = new MemoryStream(file);

                        StreamWriter st = new StreamWriter(ms);

                        string saveTo = tempDir + @"\" + statement.Title + ".pdf";
                        FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.Write);

                        int Length = 256;
                        Byte[] buffer = new Byte[Length];
                        int bytesRead = ms.Read(buffer, 0, Length);

                        while (bytesRead > 0)
                        {
                            writeStream.Write(buffer, 0, bytesRead);
                            bytesRead = ms.Read(buffer, 0, Length);
                        }
                        ms.Close();
                        writeStream.Close();

                        System.Diagnostics.Process.Start(saveTo);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show("error while opening statement (id = " + statement.Id + ")\n" + ex.StackTrace, "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }


        private void selectAccountCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (idAccount == -1)
            {
                this.importGrid.IsEnabled = true;
            }
            ComboBox cb = (ComboBox)sender;
            Account acct = (Account)cb.SelectedValue;
            idAccount = acct.Id;
            this.statements.ReplaceRange(ComptaStatementsDAO.getStatementsForAccount(idAccount));
        }

        private void fileChooser_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.RestoreDirectory = true;
            dlg.DefaultExt = ".pdf";
            dlg.Filter = "PDF Files (.pdf)|*.pdf";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                string pathCsv = dlg.FileName;
                fileName.Text = pathCsv;
            }
        }

        private void importFile_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(this.title.Text) || String.IsNullOrEmpty(this.fileName.Text))
            {
                MessageBox.Show("You must specify a file and a title before importing", "ERROR !!!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                Stream st = new FileStream(this.fileName.Text, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                ComptaStatement cs = new ComptaStatement(-1, idAccount, this.title.Text, clearDay(this.date.DateTime), DateTime.Now, st.Length);
                cs.Id = ComptaStatementsDAO.InsertStatement(cs, st);
                this.statements.Add(cs);
            }

        }

        private static DateTime clearDay(DateTime dateTime)
        {
            return new DateTime(dateTime.Year, dateTime.Month, 1);
        }

    }

    public class SizeDisplayTextConverter : IValueConverter
    {
        object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                long bitSize = (long)value;
                if (bitSize > 1000)
                {
                    bitSize = bitSize / 1024;
                    if (bitSize > 1000)
                    {
                        bitSize = bitSize / 1024;
                        return bitSize + " Mb";
                    }
                    else
                    {
                        return bitSize + " Kb";
                    }
                }
                else
                {
                    return bitSize + " b";
                }
            }
            return null;
        }

        object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }
    }
}
